import os
import socket
import subprocess

from middlewared.service import periodic, Service


def get_local_ip():
    """
    获取本机IP地址
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


class PeriodicTaskService(Service):
    class Config:
        private = True
        cli_namespace = 'system.periodic'

    # @periodic(interval=10)
    # async def get_k3s_info(self):
    #     print("----------定时获取k3s中各应用的资源耗用情况-----------1------------")
    #     # 定时获取k3s中各应用的资源耗用情况,存储数据库以备前端查询展示 # k3s kubectl top pod -A|tee -a  调整为每次获取指定时间端信息
    #     process = subprocess.Popen(['k3s', 'kubectl', 'top', 'pod', '-A'], stdout=subprocess.PIPE)
    #     # 从标准输出中读取数据
    #     output, _ = process.communicate()
    #     # 打印输出数据
    #     print(output.decode('utf-8'))
    #     # 更新数据到时序数据库文件mydatabase.rrd 中去，供前端轮询获取展示
    #
    #     print("----------定时获取k3s中各应用的资源耗用情况------------2-----------")

    @periodic(interval=float('inf'))
    async def test(self):
        # 查询出来daemon.json 和 hosts 两个文件内容,并在每次重启后写入
        self.logger.info("----------定时更新文件-----------------------")
        # 查询出来daemon.json 和 hosts 两个文件内容,并在每次重启后写入
        # 数据库中存储的数据格式为{"hosts":["14.18.33.151 harbor.local.cn"]}
        json = await self.middleware.call("keyvalue.get", "hosts", "hosts")
        hosts_contents = json["hosts"]
        print("hosts_contents=", hosts_contents)
        # 读取以前再追加数据库中的
        hosts_path = "/etc/hosts"
        if os.path.isfile(hosts_path):
            with open(hosts_path, 'a+') as f:  # 追加写
                self.logger.info("---------追加写-----------")
                f.write("\n")
                for hosts_content in hosts_contents:
                    f.write(hosts_content)
                    f.write("\n")
        else:
            with open(hosts_path, 'w') as f:  # 覆盖写
                self.logger.info("---------覆盖写-----------")
                for hosts_content in hosts_contents:
                    f.write(hosts_content)
                    f.write("\n")

    @periodic(interval=float('inf'))
    async def hccnaspush_whenstart(self):
        # 第一次安装hccnas系统启动时同步推送应用信息
        # print("-----1---hccnasstart-------")
        data_dict = {"type": "reboot", "data": {"uuid": "", "ip": "", "app_id": "", "app_name": ""}}
        await self.middleware.call('catalog.hccnas_push', str(data_dict))
        # print("-----2---hccnasstart-------")
